import { createRouter, createWebHistory } from 'vue-router';
import Home from '../pages/Home.vue';
import Detail from '../pages/Detail.vue';
import Play from '../pages/Play.vue';
import Login from '../pages/Login.vue';
import Profile from '../pages/Profile.vue';
import Favorites from '../pages/Favorites.vue';
import History from '../pages/History.vue';
import News from '../pages/News.vue';
import NewsDetail from '../pages/NewsDetail.vue';

import { useUserStore } from '../store/user';

const routes = [
  { path: '/', name: 'home', component: Home },
  { path: '/movie/:id', name: 'detail', component: Detail, props: true },
  { path: '/play/:id', name: 'play', component: Play, props: true },
  { path: '/login', name: 'login', component: Login },
  { 
    path: '/profile', 
    name: 'profile', 
    component: Profile,
    meta: { requiresAuth: true }
  },
  { 
    path: '/favorites', 
    name: 'favorites', 
    component: Favorites,
    meta: { requiresAuth: true }
  },
  { 
    path: '/history', 
    name: 'history', 
    component: History,
    meta: { requiresAuth: true }
  },
  { path: '/news', name: 'news', component: News },
  { path: '/news/:id', name: 'news-detail', component: NewsDetail },

  { path: '/:pathMatch(.*)*', redirect: '/' },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  
  if (to.meta.requiresAuth && !userStore.isLoggedIn) {
    next('/login');
  } else if (to.path === '/login' && userStore.isLoggedIn) {
    next('/');
  } else {
    next();
  }
});

export { router };